package com.pj.znt.controller;

import com.pj.project.sys_client.SysClient;
import com.pj.project.sys_client.SysClientMapper;
import com.pj.utils.sg.AjaxJson;
import com.pj.znt.config.ChatConfig;
import com.pj.znt.domain.query.ChatRequest;
import com.pj.znt.enums.ApiEndpoint;
import com.pj.znt.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 处理与聊天API的交互。
 *
 * @author 耿佳豪
 * @version 1.0
 * @since 2024-11-21
 */
@Slf4j
@RestController
public class ChatController {

    @Autowired
    private ChatService chatService;
    @Autowired
    public SysClientMapper sysClientMapper;
    @Autowired
    private ChatConfig chatConfig;
    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    /**
     * 调用聊天API接口。
     *
     * @param chatRequest 包含聊天请求信息的对象
     * @return 聊天API的响应结果
     */
    @PostMapping("/v1/chat/completions")
    public ResponseEntity<String> callChatApi(@RequestBody ChatRequest chatRequest) {
        // 检查平台是否录入
        SysClient sysClient = sysClientMapper.getById(chatRequest.getPlatformId());
        if (sysClient == null) {
            throw new RuntimeException("平台暂未录入！");
        }

        // 获取或创建话题
        AjaxJson topicResult = chatService.getOrCreateTopic(chatRequest.getChatId(), chatRequest.getUserId(), chatRequest.getPlatformId(), chatRequest.getQuestion());
        if (topicResult.getCode() == AjaxJson.CODE_ERROR) {
            throw new RuntimeException(topicResult.getMsg());
        }

        return chatService.sendChatRequest(chatRequest);
    }

    @PostMapping("/v1/chat/test")
    public ResponseBodyEmitter test(@RequestBody ChatRequest chatRequest) {
        // 检查平台是否录入
        SysClient sysClient = sysClientMapper.getById(chatRequest.getPlatformId());
        if (sysClient == null) {
            throw new RuntimeException("平台暂未录入！");
        }

        // 获取或创建话题
        AjaxJson topicResult = chatService.getOrCreateTopic(chatRequest.getChatId(), chatRequest.getUserId(), chatRequest.getPlatformId(), chatRequest.getQuestion());
        if (topicResult.getCode() == AjaxJson.CODE_ERROR) {
            throw new RuntimeException(topicResult.getMsg());
        }
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        executorService.submit(() -> {
            try {
                // 聊天API的URL
                String url = chatConfig.getUrl()+ ApiEndpoint.CHAT_COMPLETIONS.getPath();

                // 设置HTTP请求头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("Authorization", chatConfig.getAuthorization());

                // 创建HTTP请求实体
                HttpEntity<ChatRequest> entity = new HttpEntity<>(chatRequest, headers);

                // 使用RestTemplate发送POST请求
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

                // 解析响应并发送到客户端
                String responseStr = responseEntity.getBody();
                if (responseStr != null) {
                    String[] lines = responseStr.split("\n");
                    for (String line : lines) {
                        if (line.startsWith("event:")) {
                            emitter.send(line + "\n");
                        } else if (line.startsWith("data:")) {
                            emitter.send(line + "\n");
                        }
                    }
                }
                emitter.complete();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        return emitter;
    }

    /**
     * 生成话题ID。
     *
     * @return 话题ID
     */
    @PostMapping("/generateChatId")
    public AjaxJson generateChatId() {
        String ChatId = UUID.randomUUID().toString();
        return AjaxJson.getSuccessData(ChatId);
    }

    /**
     * 获取知识库详情。
     *
     * @param knowledgeBaseId 知识库ID
     * @return 知识库详情
     */
    @GetMapping("/core/dataset/detail")
    public AjaxJson getKnowledgeBaseDetails(@RequestParam String knowledgeBaseId) {
        return chatService.getKnowledgeBaseDetails(knowledgeBaseId);
    }
}